package org.dong.sys.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


@Controller
public class LoginController {

	@RequestMapping(value = {"login",""}, method = RequestMethod.GET)
	public String tologin(HttpServletRequest request,Model model) {
		Subject subject = SecurityUtils.getSubject();
		Object  principal= subject.getPrincipal();
		if(principal!=null){
			return "index";
		}
		return "login";
	}
	/**
	 * 用户登录
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(HttpServletRequest request,Model model) {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		UsernamePasswordToken token = new UsernamePasswordToken(username,
				password);
		token.setRememberMe(false);
		// 获取当前的Subject
		Subject subject = SecurityUtils.getSubject();
		Object  principal= subject.getPrincipal();
		if(principal!=null){
			subject.logout();
		}
		try {
			//登录
			subject.login(token);
			// 验证是否登录成功
			if (subject.isAuthenticated()) {
				System.out.println("用户[" + username + "]登录认证通过");
			} else {
				token.clear();
			}
		}catch (Exception e) {
			model.addAttribute("msg", "认证失败，请重新输入！");
			return "login";
		}
		return "index";
	}
	
	
    @RequestMapping(value = "/logout", method = RequestMethod.GET)  
    public String logout(HttpServletRequest request, HttpServletResponse response, Model model){  
    	Subject subject = SecurityUtils.getSubject();
        subject.logout();  
        return "redirect:/login";
    }  
}
